import 'package:flutter/material.dart';
import 'package:flutter_multi_env/models/city_model.dart';
import 'package:flutter_multi_env/multi_env.dart';
import 'package:flutter_multi_env/requests/global_request.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  /// 初始化项目环境
  CNMEvn.initEnvironment();

  /// 启动App，请求服务器地址
  RequestGlobal.requestServeData().then((_) => runApp(const MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    super.key,
    required this.title,
  });

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() => _counter++);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('城市')),
      body: FutureBuilder<List<CityModel>>(
        future: RequestGlobal.requestAllCitysData(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(
                backgroundColor: Colors.blue,
                strokeWidth: 2,
              ),
            );
          } else {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(snapshot.data![index].cityName ?? ""),
                  );
                },
              );
            } else {
              return const Center(
                child: Text("暂无城市数据"),
              );
            }
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
